/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tcp;

import java.awt.KeyboardFocusManager;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.sql.Connection;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author rdayton
 */
public class SemeskyTCPClient extends javax.swing.JFrame {

    /**
     * Creates new form SemeskyTCPClient
     */
    public SemeskyTCPClient() {
        initComponents();
        /*
         * hide fields for the option to choose a server
         */
        hostLabel.setVisible(false);
        hostField.setVisible(false);
        file1Label.setVisible(false);
        file2Label.setVisible(false);
        file2Box.setVisible(false);
        file1Box.setVisible(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        choiceBox = new javax.swing.JComboBox();
        hostField = new javax.swing.JTextField();
        hostLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        file1Area = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        file2Area = new javax.swing.JTextArea();
        file1MSLabel = new javax.swing.JLabel();
        file2MSLabel = new javax.swing.JLabel();
        file1Box = new javax.swing.JTextField();
        file1Label = new javax.swing.JLabel();
        file2Box = new javax.swing.JTextField();
        file2Label = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        choiceBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Use Default Server", "Choose Server" }));
        choiceBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                choiceBoxItemStateChanged(evt);
            }
        });

        hostField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                hostFieldFocusGained(evt);
            }
        });

        hostLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        hostLabel.setText("Host:");

        jButton1.setText("Get Files");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        file1Area.setEditable(false);
        file1Area.setColumns(20);
        file1Area.setRows(5);
        jScrollPane2.setViewportView(file1Area);

        file2Area.setEditable(false);
        file2Area.setColumns(20);
        file2Area.setRows(5);
        jScrollPane3.setViewportView(file2Area);

        file1MSLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        file2MSLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        file1Box.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                file1BoxFocusGained(evt);
            }
        });

        file1Label.setText("Filename 1:");

        file2Box.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                file2BoxFocusGained(evt);
            }
        });

        file2Label.setText("Filename 2:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 31, Short.MAX_VALUE)
                .addComponent(file1MSLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addComponent(file2MSLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(36, 36, 36)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(choiceBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hostLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(hostField, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(34, 34, 34)
                        .addComponent(file1Label)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(file1Box, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(file2Label)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(file2Box, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(choiceBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(hostField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(hostLabel)
                    .addComponent(file1Label)
                    .addComponent(file1Box, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(file2Label)
                    .addComponent(file2Box, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(45, 45, 45)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(file1MSLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(file2MSLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void choiceBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_choiceBoxItemStateChanged
            int index = choiceBox.getSelectedIndex();  
           
            //drop box is on default server
            if(index == 0)
            {
                hostLabel.setVisible(false);
                hostField.setVisible(false);
                file1Label.setVisible(false);
                file2Label.setVisible(false);
                file2Box.setVisible(false);
                file1Box.setVisible(false);
            }
            //choosing new server
            else
            {
                /*
                 * set fields to visible and show default text
                 */
                hostLabel.setVisible(true);
                hostField.setVisible(true);
                hostField.setText("www.google.com");
                file1Label.setVisible(true);
                file2Label.setVisible(true);
                file2Box.setVisible(true);
                file2Box.setText("file2.html");
                file1Box.setVisible(true);
                file1Box.setText("file1.html");
            }

    }//GEN-LAST:event_choiceBoxItemStateChanged

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
         int index = choiceBox.getSelectedIndex(); 
         String file1 = null;
         String file2 = null; 
         final int PORT=80;
         Socket connect=null;
         DataOutputStream output;
         String host = null; 
         
         //default server uses amazon IP and filenames
         if(index == 0)
         {
             host = "50.17.227.202";
             file1 = "/index.html";
             file2 = "/file2.html";
             
         }
         //get the text from the text boxes and use them
         else
         {                     
            host = hostField.getText();
            file1 = "/"+file1Box.getText();
            file2 = "/"+file2Box.getText();     
             
         }    
         //if any of the fiels are empty and the user is choosing a server then throw an error
          if((hostField.getText().isEmpty() || file1Box.getText().isEmpty() || file2Box.getText().isEmpty()) && index ==1)
            {
                    String st="Please fill in all fields";
                    JOptionPane.showMessageDialog(rootPane, st, null, JOptionPane.ERROR_MESSAGE);  

            }
          else
          {

                // get Http request function
                //String GetRequest1="GET /file1.html HTTP/1.0\r\n\r\n";
                String GetRequest1="GET "+ file1 + " HTTP/1.0\r\n\r\n";
                //tokenizer that parses the file name out of the string
                file1=tokenized(GetRequest1);
                String GetRequest2="GET "+ file2+ " HTTP/1.0\r\n\r\n";
                file2=tokenized(GetRequest2);
                //makes connection with server
                try {
                    // if(Connect(host))
                    // {
                         //downloads files by sending request
                         download(GetRequest1,GetRequest2,file1,file2, host);

                    // }
                } catch (IOException ex) {
                    Logger.getLogger(SemeskyTCPClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    }//GEN-LAST:event_jButton1MouseClicked

    private void hostFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_hostFieldFocusGained
       hostField.selectAll();
    }//GEN-LAST:event_hostFieldFocusGained

    private void file1BoxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_file1BoxFocusGained
        file1Box.selectAll();
    }//GEN-LAST:event_file1BoxFocusGained

    private void file2BoxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_file2BoxFocusGained
        file2Box.selectAll();        
    }//GEN-LAST:event_file2BoxFocusGained

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
       
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SemeskyTCPClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SemeskyTCPClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SemeskyTCPClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SemeskyTCPClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SemeskyTCPClient().setVisible(true);
            }
        });
    }  

    // file download
    private void download(final String GetRequest1,final String GetRequest2,final String file1, final String file2, final String host) throws IOException
    {
        //create a thread to get file 1
        SwingWorker worker1 = new SwingWorker() {         

            StringBuffer buf1;
            long t1;
            
            @Override
            protected Object doInBackground() throws Exception {
                
                long start = System.currentTimeMillis(); 
                
                buf1 =  executeGetRequest(GetRequest1, host);
                
                long end = System.currentTimeMillis();           
                
                t1= end-start;
                throw new UnsupportedOperationException("Not supported yet.");
                
                
            }
            
             @Override
             protected void done() {
                 //when done show the contents of the file
                file1Area.setText(buf1.toString());
                file1MSLabel.setText(t1 + " ms");
             }
        };
        
        //create a thread to get file 2
        SwingWorker worker2 = new SwingWorker() {         

            StringBuffer buf2;
            long t2;
            
            @Override
            protected Object doInBackground() throws Exception {
                
                long start = System.currentTimeMillis(); 
                
                buf2 =  executeGetRequest(GetRequest2, host);
                
                long end = System.currentTimeMillis();           
                
                t2 = end-start;                
                
                throw new UnsupportedOperationException("Not supported yet.");                
                
            }
            
             @Override
             protected void done() {
                 //when done show the contents of the file
                file2Area.setText(buf2.toString());
                file2MSLabel.setText(t2 + " ms");
             }
        };
        //start the threads
        worker1.execute();
        worker2.execute();
      
}
    
    //parses file name from the request string message
    private static String tokenized(String message)
    {			
        StringTokenizer tokenizer= new StringTokenizer(message);
        String filename = null;
	if(tokenizer.nextToken().equals("Get"))
        {
            filename=tokenizer.nextToken();

            if(filename.startsWith("/")==true)
            {
                filename=filename.substring(1);
            }
			
	}
	return filename;
}
    
    private StringBuffer executeGetRequest(String GetRequest, String host) throws IOException
    {
        StringBuffer buf1;
        
        Socket connect;
        final int PORT=80;
        DataOutputStream output;
        connect = new Socket (host, PORT); 
        
        if(connect==null)
        {
            System.out.println("Not connected to server");
        }
            
        // streams for output and input		
        output= new DataOutputStream(connect.getOutputStream());
			
        BufferedReader infromServer= new BufferedReader( new InputStreamReader(connect.getInputStream()));
			
         //send the file request			
         output.writeBytes(GetRequest);
			
         // flush the stream so no message is left on the stream
         output.flush();
             
         // get content from server
         //FileContent=infromServer.readLine();
         // reading file content and printing output
			 
          buf1 = new StringBuffer();           
          String FileContent1 = infromServer.readLine();   
			
				
          while ((FileContent1=infromServer.readLine())!=null)
          {
                buf1.append(FileContent1 + "\n");
		//System.out.println("The content of this "+file1+" file is \t"+buf1.toString());
			
           }
            
           return buf1;
            
    }
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox choiceBox;
    private javax.swing.JTextArea file1Area;
    private javax.swing.JTextField file1Box;
    private javax.swing.JLabel file1Label;
    private javax.swing.JLabel file1MSLabel;
    private javax.swing.JTextArea file2Area;
    private javax.swing.JTextField file2Box;
    private javax.swing.JLabel file2Label;
    private javax.swing.JLabel file2MSLabel;
    private javax.swing.JTextField hostField;
    private javax.swing.JLabel hostLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    // End of variables declaration//GEN-END:variables
}
